package com.example.chatchatbackend.handler;

import com.example.chatchatbackend.entity.vo.request.CommentsVO;
import com.example.chatchatbackend.entity.vo.request.SendCommentsVO;
import com.example.chatchatbackend.service.CommentsService;
import com.example.chatchatbackend.service.sendJob.SendCommentsService;
import com.example.chatchatbackend.utils.TimeUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class CommentHandler {

    @Resource
    private CommentsService advService;

    @Resource
    private SendCommentsService sendCommentsService;

    private static final LocalDateTime currentTime = TimeUtil.Time_Now.getCurrentTime();

    @XxlJob("commentTaskHandler")
    public void execute() {

        XxlJobHelper.log("Xxl-Job:Insert");

        // 查询发送时间小于当前时间且未发送的任务
        List<SendCommentsVO> tasksToSend = sendCommentsService.findTasksToSend(this.currentTime);

        if(tasksToSend.isEmpty()){
            XxlJobHelper.log("无需更新，所有记录已发送");
            return;
        }

        SendCommentsVO sendCommentsVO = tasksToSend.get(0);

        CommentsVO commentsVO = new CommentsVO();
        BeanUtils.copyProperties(sendCommentsVO, commentsVO);

        advService.insertComments(commentsVO);
        XxlJobHelper.log("成功插入Comments：{}",commentsVO);

        sendCommentsVO.setIsSend(1);
        sendCommentsService.updateSendComments(sendCommentsVO);


    }
}
